# Create your views here.
# coding: utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from MyBlog.Blog.models import *
from django.conf import  settings
from MyBlog.Blog.forms import *
from django.utils import simplejson
from django.utils.importlib import import_module

def show(request,articleId):
    article= Article.objects.get(id=articleId)
    categories=Category.objects.all()
    tags=Tag.objects.all()
    comment=Comment.objects.filter(article=article)
    content={'article':article,'categories':categories,'tags':tags,'comment':comment}
    return  render_to_response("blogs/show.html",content)

def index(request,template,c,t,p=1):
    try:
        p=int(p)
    except:
        p=1


    if c==''and t=='':
        articlelist=Article.objects.filter(state=1).order_by('-addtime')
    elif c!='':
        articlelist=Category.objects.get(id=c).article_set.filter(state=1)
    elif t!='':
        articlelist=Tag.objects.get(id=t).article_set.filter(state=1)
    categories=Category.objects.all()
    tags=Tag.objects.all()
#    arts=Category.objects.get(id=1).article_set.all()
    paginator=Paginator(articlelist,settings.ONEPAGECOUNT)
    try:
        articles=paginator.page(p)
    except(EmptyPage,InvalidPage):
        p=paginator.num_pages
        articles=paginator.page(p)
    content={'article':articles,'categories':categories,'tags':tags,'paginator':paginator,'p':p,'c':c,'t':t}
    return render_to_response(template,content)



def hit(request,articleId):
    hit=Hit(article= Article.objects.get(id=articleId))
    hit.save()
    return  HttpResponse('')

def comment(request):
    msg={'iserror':False}
    if request.method=='POST':
        form=CommentForm(request.POST)
        if form.is_valid():
            try:
                cd=form.data
                content=cd['commentcontent']
                c=Comment(article=Article.objects.get(id=cd['article']),nickname=cd['nickname'],content=content)
                c.save()
            except :
                msg['iserror']=True
                msg['msg']=u'系统内部错误'
        else:
            msg['iserror']=True
            msg['msg']=form.errors

    return HttpResponse(simplejson.dumps(msg))

